package com.cango.student.guava;


import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * https://www.jianshu.com/p/f4b99b70bd76
 * 缓存
 */
public class CacheLoaderTest {
    private LoadingCache<Integer, AtomicLong> loadingCache ;
    private final static Integer KEY = 1000;


    private final static LinkedBlockingQueue<Integer> QUEUE = new LinkedBlockingQueue<>(1000);


    private void init() throws InterruptedException {
        loadingCache = CacheBuilder.newBuilder()
                // 缓存项在给定时间内没有被写访问（创建或覆盖），则回收。
                .expireAfterWrite(10, TimeUnit.SECONDS)
                // 它可以在缓存中的条目被移除后接收通知
                .removalListener(new RemovalListener<Object, Object>() {
                    @Override
                    public void onRemoval(RemovalNotification<Object, Object> notification) {
                        System.out.println("删除原因={}，删除 key={},删除 value={}" +"  "+ notification.getCause()+"  "+notification.getKey()+"  "+notification.getValue());
                    }
                })
                .build(new com.google.common.cache.CacheLoader<Integer, AtomicLong>() {
                    @Override
                    public AtomicLong load(Integer key) throws Exception {
                        return new AtomicLong(0);
                    }
                });
//        loadingCache.put(1, new AtomicLong(1));
//        loadingCache.put(2, new AtomicLong(2));

        for (int i = 0; i < 15; i++) {
            QUEUE.put(i);
        }
    }

    private void checkAlert(Integer integer) {
        try {

            loadingCache.put(integer,new AtomicLong(integer));

            TimeUnit.SECONDS.sleep(3);


//            System.out.println("当前缓存值={},缓存大小={}"+"  "+loadingCache.get(KEY)+"  "+loadingCache.size());
//            System.out.println("缓存的所有内容={}"+"  "+loadingCache.asMap().toString());
//            loadingCache.get(KEY).incrementAndGet();
            System.out.println("当前缓存值={},缓存大小={}"+"  "+loadingCache.get(integer)+"  "+loadingCache.size());
            System.out.println("缓存的所有内容={}"+"  "+loadingCache.asMap().toString());
            loadingCache.get(integer).incrementAndGet();

        } catch (ExecutionException e ) {
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CacheLoaderTest cacheLoaderTest = new CacheLoaderTest() ;
        cacheLoaderTest.init();
        while (true) {

            try {
                // 删除头部并返回
                Integer integer = QUEUE.poll(200, TimeUnit.MILLISECONDS);
                if (null == integer) {
                    break;
                }
                //TimeUnit.SECONDS.sleep(5);
                cacheLoaderTest.checkAlert(integer);
                System.out.println("job running times=" + integer);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
